package com.xd.core.api.util;

import java.io.*;
import java.util.zip.Inflater;

/**
 * <p>
 * </p>
 *
 * @author zhuobufan
 * @version 1.0
 * @date 2022/5/30 下午3:38
 */
public class FileZipUtil {

    public static byte[] unzip(byte[] inputByte) throws IOException {
        int lth = 0;
        Inflater inf = new Inflater();
        inf.setInput(inputByte);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] oByte = new byte[1024];

        try {
            while (!inf.finished()) {
                //解压
                lth = inf.inflate(oByte);
                if(lth == 0) {
                    break;
                }
                bos.write(oByte, 0, lth);
            }
        } catch (Exception e) {
            System.out.println("解压文件异常"+ e.getMessage());
//
        } finally {
            bos.close();
        }
        return bos.toByteArray();
    }

    public static void unzip(byte[] inputByte, File file) throws IOException {
        int lth = 0;
        FileOutputStream fs = new FileOutputStream(file);
        byte[] oByte = new byte[1024];

        try {
            while (true) {
                fs.write(oByte, 0, inputByte.length-1);
            }
        } catch (Exception e) {
            System.out.println("解压文件异常");
//
        } finally {
            fs.close();
        }
    }
    public static void file(byte[] inputByte, File file) throws IOException {
        FileOutputStream fs = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fs);
        try {
            bos.write(inputByte);
        } catch (Exception e) {
            System.out.println("解压文件异常");
//
        } finally {
            bos.close();
            fs.close();
        }
    }
    public static void decompress(byte[] bytes, File file) throws IOException {
        FileOutputStream fs = new FileOutputStream(file);
        Inflater inflater = new Inflater();
        //设置待解压数据
        inflater.setInput(bytes);
        byte[] buf = new byte[1024];
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try  {
            //是否已解压完成
            while (!inflater.finished()) {
                //解压
                int len = inflater.inflate(buf);
                output.write(buf, 0, len);
            }
            //关闭资源
            inflater.end();
            fs.write(output.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}